﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using University.Workshop.Model;
using University.Workshop.DataAccess;
using System.Text.RegularExpressions;

namespace University.Workshop.Business
{
    public static class WatchListManager
    {
        public static Collection<WatchListItem> AddToWatchList(long productId, long userId, string comment,Collection<WatchListItem> list)
        {
            if (list != null)
            {

                string pattern=@"^[a-zA-Z 0-9]";
                WatchListItem item = new WatchListItem();
                if (!String.IsNullOrEmpty(comment))
                {
                    if (!Regex.IsMatch(comment, pattern))
                    {
                        throw new ValidationException("Incorrect format input text");
                    }
                }
                else
                {
                    item.Comment = null; 
                }
                WatchListDataAccess.InsertProduct(userId, productId, comment);
                Product product = ProductDataAccess.GetProductById(productId);
                
                item.RelatedProduct = product;
                item.UserId = userId;
                item.Comment = comment;
                list.Add(item);
                /*User user = UserDataAccess.GetUserById(userId);
                string body = "Yo have added " + product.Name + "to your watch list";
                EmailSender.SendEmail(user.ContactInformation.Email, user.PersonalInformation.FirstName+" "+user.PersonalInformation.LastName, body);
            */
                 }
            return list;
        }

        public static Collection<WatchListItem> AddComment(long productId, long userId, string comment, Collection<WatchListItem> list)
        {
            WatchListDataAccess.ModifyComment(userId, productId, comment);
            list = WatchListDataAccess.GetList(userId);
            return list;
        }
        public static Collection<WatchListItem> RemoveItem(long userId, long productId, Collection<WatchListItem> list)
        {
            if (list != null)
            {
                WatchListItem toRemove = null;
                WatchListDataAccess.DeleteProduct(userId, productId);
                foreach (var item in list)
                {
                    if (item.RelatedProduct.ProductId == productId)
                    {
                        toRemove = item;
                        break;
                    }
                }
                list.Remove(toRemove);
            }
            return list;
        }

    }
}
